package com.ecommerce.web.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.ecommerce.dal.entity.Customer;

public class CustomerRegistrationValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		// just validate the Customer instances
		return Customer.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "CustomerRegistration.required.firstName");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "CustomerRegistration.required.lastName");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthDate", "CustomerRegistration.required.birthDate");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender", "CustomerRegistration.required.gender");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "CustomerRegistration.required.userName");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "CustomerRegistration.required.password");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cpassword", "CustomerRegistration.required.cpassword");
		
		Customer customer = (Customer) target;

		if (!(customer.getPassword().equals(customer.getCpassword()))) {
			errors.rejectValue("cpassword", "CustomerRegistration.notmatch.password");
		}

		if (customer.getUserName().length() < 5) {
			errors.rejectValue("userName", "CustomerRegistration.required.userNameLength");
		}

		//TODO
		/*Calendar c = Calendar.getInstance();
		c.setTime(customer.getBirthDate());
		int year = c.get(Calendar.YEAR);
		
		if ("NONE".equals(customer.getAge() < 18)) {
			errors.rejectValue("age", "required.minAge");
		}*/
	}
}
